﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RegexLib.Web.Models.Web;
using RegexLib.Web.Models.Data;

namespace RegexLib.Web.Controllers
{
	public class KeywordsController : Controller
	{
		/// <summary>
		/// 查看所有关键字。
		/// </summary>
		/// <returns></returns>
		public ActionResult Index()
		{
			var allKeywords = RxKeywords.GetTopUseKeywords(-1);
			ViewData["AllKeywords"] = allKeywords;
			return View("KeywordsIndex");
		}

		/// <summary>
		/// 查看某个具体的关键字页面。
		/// </summary>
		/// <param name="text"></param>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public ActionResult ViewKeyword(string text, int pageIndex, int pageSize)
		{
			KeywordInfo ki = RxKeywords.GetKeywordByText(text.Replace('+', ' '));
			if (ki == null)
				ki = RxKeywords.GetKeywordByText(text);

			int totalPages;
			RegexInfo[] rx = ki.GetRegex(pageIndex, pageSize, out totalPages);

			UserInfo contributedUser;
			using (RxDataContext db = new RxDataContext())
			{
				contributedUser = db.UserInfos.FirstOrDefault(u => u.UserId == ki.ContributedUserId);
			}

			KeywordInfo[] relativeKeywords = ki.GetRelativeKeywords();

			ViewData["PageIndex"] = pageIndex > 0 ? pageIndex : totalPages;
			ViewData["PageSize"] = pageSize;
			ViewData["TotalPages"] = totalPages;
			ViewData["Regexes"] = rx;
			ViewData["Keyword"] = ki;
			ViewData["ContributedUser"] = contributedUser;
			ViewData["RelativeKeywords"] = relativeKeywords;

			return View();
		}
	}
}
